<?php

namespace App\Workers;

use App\Services\CollegeOtherDataUpdateSpiderService;
use Workerman\Worker;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class CollegeOtherDataUpdateSpiderWorker
{
    protected static ?Logger $logger = null;

    public static function run(Worker $worker, $limit = 0): void
    {
        self::initLogger();

        $worker->onWorkerStart = function($worker) use ($limit) {
            try {
                self::$logger->info("Worker启动", [
                    'pid' => getmypid(),
                    'limit' => $limit
                ]);

                $spider = new CollegeOtherDataUpdateSpiderService();
                $spider->crawlAllColleges();

            } catch (\Throwable $e) {
                self::handleFatalError($e, $worker);
            }
        };
    }

    protected static function initLogger(): void
    {
        if (!self::$logger) {
            $logDir = dirname(__DIR__, 2) . '/storage/logs';
            self::$logger = new Logger('高考数据信息整理Worker');
            self::$logger->pushHandler(new StreamHandler($logDir.'/college-other-data-worker.log'));
        }
    }

    protected static function handleFatalError(\Throwable $e, Worker $worker): void
    {
        self::$logger->error("Worker运行异常", [
            'error' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
            'memory_usage' => round(memory_get_usage(true) / 1024 / 1024, 2).'MB'
        ]);

        $worker->stop();
    }
}
